<template>
    <div class="form">
        <el-form :model="formData" :rules="formRules" ref="formRef" :show-message="false">
            <el-form-item prop="username">
                <el-input v-model.trim="formData.username" clearable placeholder="用户名" maxLength="32" @keyup.enter.native="enterKey($event, 'M1')"></el-input>
            </el-form-item>
            <el-form-item prop="password">
                <el-input type="password" v-model.trim="formData.password" clearable placeholder="密码" maxLength="32" ref="M1" @keyup.enter.native="enterKey($event, 'M2')"></el-input>
            </el-form-item>
            <el-form-item prop="verifyCode" class="none verifyCode">
                <el-input v-model.trim="formData.verifyCode" clearable placeholder="验证码" maxLength="4" ref="M2" @keyup.enter.native="save('formRef')"></el-input>
                <v-identify class="codeBtn" :identifyCode="identifyCode" @click.native="refreshCode" />
            </el-form-item>
            <el-form-item class="none">
                <el-checkbox v-model="isRemember">
                    <span style="color: #666;">记住用户名</span>
                </el-checkbox>
                <span class="right forgotText" @click="$store.commit('loginStore/updateStatus', 6)">忘记密码？</span>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="save('formRef')">密码登录</el-button>
            </el-form-item>
        </el-form>
        <!-- 其它登录方式 -->
        <div class="otherLogType">
            <span>其它登录方式：</span>
            <img src="../../assets/images/icon-wx.png" title="微信登录" alt="">
            <img src="../../assets/images/icon-qq.png" title="qq登录" alt="">
            <img src="../../assets/images/icon-phone.png" title="手机号登录" alt="" @click="$store.commit('loginStore/updateStatus', 4)">
        </div>
    </div>
</template>
<script>
import identify from '../identify'
export default {
    components: {
        'v-identify': identify
    },
    data() {
        return {
            formData: {},
            formRules: {
                username: [{required: true, triggle: 'blur'}],
                password: [{required: true, triggle: 'blur'}],
                verifyCode: [{required: true, triggle: 'blur'}]
            },
            isRemember: true,       //是否记住用户名
            isDisabled: true,       //是否禁用验证码按钮
            identifyCodes: "1234567890abcdefghjkmnpqrstuvwxy",
            identifyCode: '',		//验证码
        }
    },
    methods: {
        refreshCode() {     //刷新验证码
            this.identifyCode = "";
            this.makeCode(this.identifyCodes, 4);
        },
        makeCode(o, l) {		//生成验证码
            for (let i = 0; i < l; i++) {
                this.identifyCode += this.identifyCodes[this.randomNum(0, this.identifyCodes.length)];
            }
        },
        randomNum(min, max) {		//产生随机数
            return Math.floor(Math.random() * (max - min) + min);
        },
        save(formName) {        //登录
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    //校验验证码是否正确
                    if(this.formData.verifyCode.toLowerCase() !== this.identifyCode) {
                        this.$notify({message: '验证码错误', type: 'warning', duration: '1500', offset: 30});
                        this.refreshCode();
                        return false;
                    }
                    delete this.formData['verifyCode'];
                    //后台校验
                    this.$http({
                        method: 'post',
                        url:  'login/loginUser',
                        params: this.formData
                    }).then(res => {
                        if(res.data.code == 20001) {
                            this.$notify({message: '登录成功', type: 'success', duration: '1500', offset: 30});
                            //存储登录信息
                            sessionStorage.setItem('isLogin', JSON.stringify(res.data.data));
                            if(this.isRemember) {
                                let uInfo = JSON.parse(localStorage.getItem('uInfo'));
                                if(uInfo) {
                                    uInfo['username'] = this.formData['username'];
                                    localStorage.setItem('uInfo', JSON.stringify(uInfo));
                                } else {
                                    //不存在时，创建uInfo对象
                                    localStorage.setItem('uInfo', JSON.stringify({username: this.formData['username']}));
                                }
                            } else {
                                let uInfo = JSON.parse(localStorage.getItem('uInfo'));
                                if(uInfo) {
                                    delete uInfo['username'];
                                    if(JSON.stringify(uInfo) == '{}') {
                                        localStorage.removeItem('uInfo');
                                    } else {
                                        localStorage.setItem('uInfo', JSON.stringify(uInfo));
                                    }
                                } else {
                                    localStorage.removeItem('uInfo');
                                }
                            }
                            setTimeout(() => {
                                this.$router.push('/');     //跳转到首页
                            }, 1000);
                        } else {
                            this.$alert(res.data.msg || '登录失败', '登录提示', {
                                confirmButtonText: '确定'
                            });
                            this.refreshCode();
                        }
                    });
                }
            });
        },
        enterKey(lastRef, nextRef) {        //回车键换行
            if(lastRef.target.value) {
                this.$refs[nextRef].focus();
            }
        }
    },
    created() {
        let uInfo = JSON.parse(localStorage.getItem('uInfo'));
        if(uInfo && uInfo['username']) {
            this.formData['username'] = uInfo['username'];
        }
        this.makeCode(this.identifyCodes, 4);
    }
}
</script>